package data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseManage {
    private static final String URL="jdbc:mysql://localhost:3306/translation";
    private static final String NAME="v";
    private static final String PWD="008748";

    //用ThreadLocal来管理多个线程的与数据库进行的connection链接
    private static ThreadLocal<Connection> connectionHolder
            =new ThreadLocal<Connection>() {
        public Connection initialValue() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                return DriverManager.getConnection(URL, NAME, PWD);
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        }

        @Override
        public void remove() {
            try {
                Connection connection=connectionHolder.get();
                super.remove();
                connection.close();
            }catch (SQLException ex){
                ex.printStackTrace();
            }
        }

    };

    //获取connection
    public static Connection getConnection(){
        try {
            if(!connectionHolder.get().isValid(10)) {
                connectionHolder.remove();
            }
        }catch (SQLException ex){
            ex.printStackTrace();
        }

        return connectionHolder.get();
    }
}
